package storeSorting

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"github.com/shopspring/decimal"
	"gorm.io/gorm"
	"insighttracking/apps/sorting/auth"
	"insighttracking/common/utils"
	"insighttracking/query/dao"
	"insighttracking/query/model"
	"insighttracking/query/service"
	"net/http"

	"insighttracking/apps/sorting/internal/svc"
	"insighttracking/apps/sorting/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type CreateStoreSortingApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewCreateStoreSortingApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *CreateStoreSortingApiLogic {
	hostname, _ := os.Hostname()
	return &CreateStoreSortingApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *CreateStoreSortingApiLogic) CreateStoreSortingApi(req *types.CreateStoreSortingReq) (resp string, err error) {
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return "", err
	}

	for _, item := range req.DataList {
		ordersEntity, err := service.OrdersService.GetByIdApi(l.ctx, item.OrdersID)
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return "", errors.New("传递的订单id错误")
		}
		//ordersDetailEntity, err := service.OrdersDetailService.GetByIdApi(l.ctx, item.OrdersDetailId)
		//if errors.Is(err, gorm.ErrRecordNotFound) {
		//	return "", errors.New("传递的订单详情id错误")
		//}
		// OrdersDetailId 其实是spuID
		spu, err := service.SpuService.GetBySpuIdApi(l.ctx, item.SpuId)

		tx := dao.Use(l.svcCtx.MysqlDb).Begin()
		outboundCount, _ := decimal.NewFromString(item.OutboundCount)

		sortingEntity, err := service.StoreSortingService.GetStoreSortingByOrderIdApi(l.ctx, item.OrdersID)
		var storeSortingId int64
		if errors.Is(err, gorm.ErrRecordNotFound) {
			l.Logger.Infof("--------------------第一次创建--------------------")
			// 第一次
			storeSortingEntity := model.StoreSortingEntity{
				OrderNo:      utils.GenerateTodayOrderNo(l.svcCtx.RedisDb, "FJCK"), // 订单流水号
				EnterpriseID: accountInfo.EnterpriseId,                             // 关联到enterprise表主键id
				CustomerID:   ordersEntity.CustomerID,                              // 客户id,关联到enterprise_customer表主键id
				TotalAmount:  spu.SalesPrice.Mul(outboundCount),                    // 订单金额
				TotalCount:   outboundCount,                                        // 订单商品数量
				WarehouseID:  ordersEntity.WarehouseID,                             // 出库仓库,关联到warehouse表主键id
				OrdersID:     item.OrdersID,                                        // 关联到订单表id,orders表主键id
				OperateName:  accountInfo.PersonName,                               // 制单员
				OperateID:    accountInfo.PersonId,                                 // 制单员id,关联到员工表
				Remark:       item.Remark,                                          // 备注
			}
			if err = service.StoreSortingService.CreateApi(l.ctx, tx, &storeSortingEntity); err != nil {
				if err = tx.Rollback(); err != nil {
					return "", err
				}
				return "", errors.New("创建失败")
			}
			storeSortingId = storeSortingEntity.ID
		} else {
			l.Logger.Infof("-------------------第二次创建-------------------")
			// 更新数量和金额
			totalCount := sortingEntity.TotalCount.Add(outboundCount)
			totalAmount := sortingEntity.TotalAmount.Add(spu.SalesPrice.Mul(outboundCount))
			if err = service.StoreSortingService.ModifyByIdApi(l.ctx, tx, sortingEntity.ID, totalCount, totalAmount); err != nil {
				if err = tx.Rollback(); err != nil {
					return "", err
				}
				return "", err
			}
			storeSortingId = sortingEntity.ID
		}
		// 创建明细
		var storeSortingDetailEntity = make([]*model.StoreSortingDetailEntity, 0)

		unitName, _ := service.SpuService.GetUnitNameBySpuIdApi(l.ctx, spu.ID)
		spuMap, _ := service.OrdersDetailService.GetTotalSpuApi(l.ctx, []int64{item.OrdersID})
		if spuMap == nil || len(spuMap) == 0 {
			return "", errors.New("参数有误，该订单没有下此类商品")
		}
		storeSortingDetailEntity = append(storeSortingDetailEntity, &model.StoreSortingDetailEntity{
			StoreSortingID: storeSortingId, // 分拣单store_sorting主键id
			//OrdersDetailID:          item.OrdersDetailId,                        // 关联到orders_detail表主键id
			SpuID:                   spu.ID,                  // 商品,关联到spu表主键id
			SnapshotSpuName:         spu.Name,                // 快照商品名称
			SnapshotProductImageURL: spu.ProductImageURL,     // 快照产品图片
			SnapshotSpuType:         spu.SpuType,             // 快照商品类型,0表示基础商品,1表示加工商品
			SnapshotUnit:            unitName,                // 快照单位
			SnapshotCategoryID:      spu.CategoryID,          // 快照分类id
			SnapshotCategory:        spu.CategoryName,        // 快照分类
			LossRate:                spu.LossRate,            // 快照损耗率
			OrdersCount:             spuMap[spu.ID].Count,    // 下单数量
			OutboundCount:           outboundCount,           // 出库数量
			SnapshotPrice:           spu.SalesPrice,          // 快照商品单价
			OperateName:             accountInfo.PersonName,  // 出库员
			OperateID:               accountInfo.PersonId,    // 出库员id,关联到员工表
			Remark:                  "",                      // 备注
			UUID:                    utils.UuIdV4(),          // 唯一识别
			ProductionDetailID:      item.ProductionDetailId, // 生产计划ID
		})
		if err = service.StoreSortingDetailService.CreateBatchApi(l.ctx, tx, storeSortingDetailEntity); err != nil {
			return "", errors.New("创建失败")
		}

		if err = tx.Commit(); err != nil {
			return "", err
		}
		//ordersDetailEntities, err := service.OrdersDetailService.GetByOrderIdListApi(l.ctx, []int64{item.OrdersID})
		//if err == nil && len(ordersDetailEntities) > 0 {
		//	if k.Every(ordersDetailEntities, func(item *model.OrdersDetailEntity, index int) bool {
		//		return item.Status == enum.OrdersSortingFinishEnum
		//	}) {
		//		// 等全部订单详情都分拣完成订单才改分拣
		//		if err = service.OrdersService.ModifyStatusByIdApi(l.ctx, nil, []int64{item.OrdersID}, enum.OrdersSortingFinishEnum); err != nil {
		//			l.Errorf("修改状态失败:[%v]", err)
		//		}
		//	} else if err = service.OrdersService.ModifyStatusByIdApi(l.ctx, nil, []int64{item.OrdersID}, enum.OrdersSortingProgressEnum); err != nil {
		//		l.Errorf("修改状态失败:[%v]", err)
		//	}
		//}
	}
	return "操作成功", nil
}
